#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"


//创建
hash hash_create(){
    hash h = (hash)malloc(sizeof(struct hash_node));
    if (h == NULL) {
	printf("malloc hash failed\n");
	return NULL;
    }

    memset(h, 0, sizeof(hash));

    return h;
}

//放入数据
int hash_insert(hash h, data_type key){
    if (h == NULL) {
	printf("hash is NULL\n");
	return -1;
    }

    linklist p = (linklist)malloc(sizeof(listnode));
    if (p == NULL) {
	printf("malloc linklist NULL\n");
	return -1;
    }

    p->key = key;
    p->value = key % N;
    p->next = NULL;

    linklist q = &(h->data[key % N]);

    while (q->next && q->next->key < p->key)
	q = q->next;

    //两种可能，1.头链表q中没有数据,即在后节点连上，2.有数据，进行key比较
    p->next = q->next;
    q->next = p;

    return 1;
}

//判断某数据是否存在
linklist hash_search(hash h, data_type key){
    if (h == NULL) {
	printf("hash is NULL\n");
	return NULL;
    }

    linklist p = &(h->data[key % N]);

    while (p->next && p->next->key != key)
	p = p->next;

    return p->next == NULL ? NULL : p->next;
}
